package com.jmb.apiplatform.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jmb.apiplatform.common.LoginUserInfo;
import com.jmb.apiplatform.common.PageResult;
import com.jmb.apiplatform.exception.ValidException;
import com.jmb.apiplatform.mapper.UserMapper;
import com.jmb.apiplatform.pojo.UserDao;
import com.jmb.apiplatform.pojo.UserVO;
import com.jmb.apiplatform.service.UserService;
import com.jmb.apiplatform.util.MD5Util;
import com.jmb.apiplatform.util.RedisUtil;
import com.jmb.apiplatform.util.ValidUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service
@Slf4j
public class UserServiceImpl  implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LoginUserInfo loginUserInfo;


    @Override
    public void registerUserInfo(UserDao userDao) throws ValidException {
        String userName = userDao.getUsername();
        String password = userDao.getPassword();
        Date date = new Date();
        userDao.setName(userName);
        userDao.setCreatedTime(date);
        userDao.setUpdateTime(date);
        userDao.setEnable(1);
        userDao.setSex(1);
        ValidUtil.notNUll(password, "用户密码不能为空");
        ValidUtil.length(password,6,20,"密码长度在6-20之间");
        if (userMapper.selectUserByName(userName)!=null){
            throw new ValidException("用户名已存在");
        } else {
            userDao.setPassword(MD5Util.md5ForLoginPassword(password));
            userMapper.insetUser(userDao);
        }
    }

    @Override
    public UserDao loginUser(UserDao userDao) throws ValidException {
        String username = userDao.getUsername();
        String password = userDao.getPassword();
        UserDao dbuser = userMapper.selectUserByName(username);
        ValidUtil.notNUll(dbuser, "用户名不存在");
        userDao.setUsername(username);
        String md5password=MD5Util.md5ForLoginPassword(password);
        if (!md5password.equals(dbuser.getPassword())){
            throw new ValidException("密码不正确");
        }else {
            userDao.setPassword(md5password);
            return userMapper.LoginUser(userDao);
        }
    }

    @Override
    public void LoginOut(String key) {
        redisUtil.del(key);
    }


    @Override
    public void saveUser(UserDao userDao) throws ValidException {
        String username = userDao.getUsername();
        String password = userDao.getPassword();
        Date date = new Date();
        userDao.setCreatedTime(date);
        userDao.setUpdateTime(date);
        userDao.setEnable(1);
        if (userMapper.selectUserByName(username)!=null){
            throw  new ValidException("账号已存在");
        }
        else {
            ValidUtil.notNUll(password,"密码不能为空");
            ValidUtil.length(password,6,20,"密码长度在6-20之间");
            userDao.setPassword(MD5Util.md5ForLoginPassword(password));
            ValidUtil.notNUll(userDao.getJob(),"工号不能为空");
            userMapper.save(userDao);
        }
    }

    @Override
    public void changePwd(HttpServletRequest request, String oldPwd, String newPwd) throws ValidException {
        String realName = loginUserInfo.getRealName(request);
        System.out.println("realName:"+realName);
        // 1. 我们先看传入的密码是否为空
        if (oldPwd==null || newPwd==null){
            throw new ValidException("密码不能为空");
        }
        // 2. 密码长度是否在6-20之间
        ValidUtil.length(newPwd,6,20,"密码长度在6-20之间");
        // 3. 旧密码是否正确
        HashMap<String, Object> userMap = (HashMap) loginUserInfo.getUserToken(request);
        Integer userId = (Integer) userMap.get("userId");
        String token = (String)userMap.get("token");
        String pwdByUserId = userMapper.selectPwdByUserId(userId);
        if (!MD5Util.md5ForLoginPassword(oldPwd).equals(pwdByUserId)){
            throw new ValidException("旧密码不正确");
        }
        // 4. 插入新密码
        userMapper.changePwd(userId,MD5Util.md5ForLoginPassword(newPwd));
        // 5.密码更改之后，清除token，使账号退出
        redisUtil.del(token);
    }

    @Override
    public void pwdReset(Integer userId, String defaultPwd) throws ValidException {
        if (userId==1){
            throw new ValidException("管理员账号不允许重置");
        }
        ValidUtil.length(defaultPwd,6,20,"密码长度在6-20之间");
        userMapper.pwdReset(userId,MD5Util.md5ForLoginPassword(defaultPwd));

    }

    @Override
    public void modifyUser(UserDao userDao) throws ValidException {
        if (!userMapper.checkUser(userDao).isEmpty()){
            throw new ValidException("员工账号已存在");
        }
        // 1. 管理员账号无法修改
        if (userDao.getUserId()==1){
            throw new ValidException("管理员账号不允许修改");
        }


        // 3.插入数据
        userDao.setUpdateTime(new Date());
        userMapper.editUser(userDao);
    }

    @Override
    public UserDao infoUserById(Integer userId) throws ValidException {
        UserDao userDao = userMapper.findById(userId);
        if (userDao ==null){
            throw new ValidException("用户不存在");
        }
        return userDao;
    }

    @Override
    public PageResult listUser(UserVO userVO) {
        log.info("UserVO 传入的参数是：{}", JSON.toJSONString(userVO));
        PageHelper.startPage(userVO.getPageNum(), userVO.getPageSize());
        List<UserDao> userDaoList = userMapper.list(userVO);
        Page<UserDao> p =(Page<UserDao>) userDaoList;
        return new PageResult(p.getTotal(),p.getResult());
    }

    @Override
    public void removeUserById(HttpServletRequest request, Integer userId) throws ValidException {
        if (userId==1){
            throw new ValidException("管理员账号不允许删除");
        }

        Object userToken = loginUserInfo.getUserToken(request);
        log.info("删除用户,删除用户token为:{}", JSON.toJSONString(userToken));
        userMapper.removeUserById(userId);

    }
}




